package edu.example.manage.servlet;

import com.google.gson.Gson;
import edu.example.Vo.UserVo;
import edu.example.common.PowerCheck;
import edu.example.common.ResponseData;
import edu.example.manage.annotation.MyDefineMapper;
import edu.example.manage.utils.JDBCUtils;
import edu.example.pojo.Check;
import edu.example.pojo.Users;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class RoomMangeServlet {
    private static final JDBCUtils jdbcUtils = JDBCUtils.createConnection();

    /**
     * 执行获取用户列表的方法
     * @param req
     * @param resp
     */
    @MyDefineMapper("room_manage_list")
    public void getRoomManageList(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("执行获取getRoomManageList方法中");

        // 页面展示长度
        Integer pages = Integer.valueOf(req.getParameter("pages"));
        Integer pageNum = Integer.valueOf(req.getParameter("pageNum"));
        try {
            // 查询
            String searchText = req.getParameter("searchText");
            System.out.println(searchText);
            String sql = "select stucode, name, gender, role from user where ? = 'null' or name = ? limit ?, ?";
            List<Users> reslut = (ArrayList<Users>) jdbcUtils.queryList(sql, Users.class, searchText, searchText, pages, pageNum);
            // 转换身份成文本
            List<UserVo> reList = new ArrayList<>();
            for (Users users : reslut) {
                reList.add(amelssbleUserVo(users));
            }
            // 返回结果
            resp.getWriter().write(ResponseData.toSuccess(reList));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("404");
        }
    }

    /**
     * 执行获取用户详细信息的方法
     * @param req
     * @param resp
     */
    @MyDefineMapper("detailed")
    public void getDetailedUserDetails(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Integer id = Integer.valueOf(req.getParameter("stucode"));
            String sql = "select stucode, name, gender, password, phone, role, buildings_card as buildingsCard, rooms_card as roomsCard from user where stucode = ?";
//            UserVo users = amelssbleUserVo((Users) jdbcUtils.query(sql, Users.class, id));
//            resp.getWriter().write(ResponseData.toSuccess(users));
            resp.getWriter().write(ResponseData.toError(jdbcUtils.query(sql, Users.class, id)));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败");
        }
    }

    /**
     * 将数据库中存放的格式转换成用户看得懂的形式
     * @param user
     * @return
     */
    private UserVo amelssbleUserVo(Users user) {
        UserVo result = new UserVo();
        result.setStucode(user.getStucode());
        result.setGender(user.getGender());
        result.setName(user.getName());
        result.setPassword(user.getPassword());
        result.setPhone(user.getPhone());
        result.setRoomsCard(user.getRoomsCard());
        result.setBuildingsCard(user.getRoomsCard());
        result.setUserID(user.getUserID());

        String text = "";
        switch (user.getRole()) {
            case 0:
                text = "学生";
                break;
            case 1:
                text = "宿管";
                break;
            case 2:
                text = "超级管理员";
                break;
        }
        result.setRole(text);
        return result;
    }

    /**
     * 进行更新的操作
     * @param req
     * @param resp
     */
    @MyDefineMapper("update")
    public void updateUserWait(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        String json = req.getReader().lines().collect(Collectors.joining());
        Gson gson = new Gson();
        Integer objId = gson.fromJson(json, UserVo.class).getStucode();

        // 验证权限以保证不会越权
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        // 提交更新操作
        submitCheck(resp, "insert into `check`(type, message, obj_type, execution, obj) value(?, ?, ?, ?, ?)",
                objId, 0, json, 0, 1, objId);
    }

    /**
     * 进行删除的操作
     * @param req
     * @param resp
     * @throws IOException
     * @throws SQLException
     */
    @MyDefineMapper("delete")
    public void deleteUserWait(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        String json = req.getReader().lines().collect(Collectors.joining());
        Gson gson = new Gson();
        Integer objId = gson.fromJson(json, UserVo.class).getStucode();

        // 验证权限以保证不会越权
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        // 提交审核信息
        submitCheck(resp, "insert into `check`(type, message, obj_type, execution, obj) value(?, ?, ?, ?, ?)",
                    objId, 0, json, 0, 0, objId);
    }

    /**
     * 提交审核信息
     * @param resp
     * @param sql
     * @param objId
     * @param params
     * @throws SQLException
     * @throws IOException
     */
    public void submitCheck(HttpServletResponse resp,
                            String sql, Integer objId, Object... params) throws SQLException, IOException {

        // 判断是否具有重复提交的
        Object o = jdbcUtils.query("select * from `check` where obj = ? and type = 0", Check.class, objId);
        if (o != null) {
            resp.getWriter().write(ResponseData.toError("该对象正在审核中"));
            return;
        }

        int update = jdbcUtils.update(sql, params);
        String text = null;
        if (update == 0) {
            text = "未知原因操作失败";
        }
        resp.getWriter().write(ResponseData.toDomain(update, null, text));
    }
}
